package com.yeskery.nut.websocket;

import com.yeskery.nut.core.*;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;

/**
 * WebSocket配置会话对象
 * @author sprout
 * @version 1.0
 * 2023-04-22 15:17
 */
public abstract class BaseWebSocketServerConfigureSession extends BaseSession {

    /** WebSocket服务端配置项对象 */
    private final WebSocketServerConfigure webSocketServerConfigure;

    /** 路径参数map */
    private Map<String, String> pathParameterMap = null;

    /**
     * 构建路径参数WebSocket会话对象
     * @param path 请求路径
     * @param params 请求参数
     * @param webSocketServerConfigure WebSocket服务端配置项对象
     */
    public BaseWebSocketServerConfigureSession(String path, Map<String, List<String>> params, WebSocketServerConfigure webSocketServerConfigure) {
        super(path, params);
        this.webSocketServerConfigure = webSocketServerConfigure;
    }

    @Override
    public Map<String, String> getPathParameters() {
        if (pathParameterMap != null) {
            return pathParameterMap;
        }
        pathParameterMap = new HashMap<>(16);
        PathMetadata pathMetadata = webSocketServerConfigure.getPathMetadata();
        DynamicRegisterMetadata dynamicRegisterMetadata = new DynamicRegisterMetadata(
                Arrays.stream(pathMetadata.getParamNameAndPatterns()).map(KeyAndValue::getKey).toArray(String[]::new),
                new PathMatcher(pathMetadata.getPathPattern()));
        if (dynamicRegisterMetadata.getPathMatcher().match(getRequestPath())) {
            Matcher matcher = dynamicRegisterMetadata.getPathMatcher().getMatcher();
            for (int i = 0; i < dynamicRegisterMetadata.getPathParameterNames().length; i++) {
                String key = dynamicRegisterMetadata.getPathParameterNames()[i];
                String value = matcher.group(i + 1);
                pathParameterMap.put(key, value);
            }
        }
        return pathParameterMap;
    }
}
